package com.example.james.fragmentbestpractice;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * Created by James on 1/25/2018.
 */

public class NewsTitleFragment extends Fragment {
    private boolean isTwoPage;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.news_title_frag, container, false);
//        RecyclerView newsTitleRecyclerView = view.findViewById(R.id.news_title_recycler_view);
//        NewsTitleAdapter newsTitleAdapter = new NewsTitleAdapter(getNews(), isTwoPage, getFragmentManager());
//        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
//        newsTitleRecyclerView.setLayoutManager(linearLayoutManager);
//        newsTitleRecyclerView.setAdapter(newsTitleAdapter);
        return view;
    }

    private List<News> getNews() {
        List<News> newsList = new ArrayList<>();
        for (int i = 0; i < 50; i++){
            News news = new News();
            news.setTitle("This is news title " + i);
            news.setContent(getRandomLengthContent("This is news content " + i));
            newsList.add(news);
        }
        return newsList;
    }

    private String getRandomLengthContent(String s) {
        Random random = new Random();
        int length = random.nextInt(20) + 1;
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < length; i++){
            builder.append(s);
        }
        return builder.toString();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (getActivity().findViewById(R.id.news_content_layout) != null){
            isTwoPage = true;
        } else {
            isTwoPage = false;
        }
        RecyclerView newsTitleRecyclerView = getActivity().findViewById(R.id.news_title_recycler_view);
        NewsTitleAdapter newsTitleAdapter = new NewsTitleAdapter(getNews(), isTwoPage, getFragmentManager());
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        newsTitleRecyclerView.setLayoutManager(linearLayoutManager);
        newsTitleRecyclerView.setAdapter(newsTitleAdapter);
    }
}
